﻿/* ********************************************************************************
 * 名称：SysModule_RepositoryService
 * 描述：系统模块表  仓储服务接口实现类（本类通过CodeSmith软件生成生成）
 * 创建人：HFL
 * 创建日期：2020-06-01 17:48:55
 * 修改人：
 * 修改日期：
 * *******************************************************************************/
using WPay.Domain.MainModule.Interface.RepositoryServices;
using WPay.Domain.Model.DTOs;
using WPay.Domain.Model.Entities;
using WPay.Infrastructure.Repository.Base;
using WPay.Infrastructure.Repository.DapperCore;
using WPay.Infrastructure.Unity;
using Dapper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Model.DTO.Manager;
using System.Linq;
using WPay.Infrastructure.EFCore;
using WPay.Domain;
using Models.DTO.Api;

namespace WPay.Infrastructure.Repository.MainModule
{
    /// <summary>
    /// 系统模块表 仓储服务接口实现类
    /// </summary>
    public class SysModule_RepositoryService : RepositoryBase, ISysModule_RepositoryService
    {
        /// <summary>
        /// 查询SQL语句
        /// </summary>
        private readonly string querySql = @"select ID,PID,ModuleName,ModuleUrl,OrderID,ModuleCls,IsDeleted,CreateTime from SysModule where 1=1";
        /// <summary>
        /// 查询数据条数SQL语句
        /// </summary>
        private readonly string queryCountSql = @"select count(1) from SysModule where 1=1";
        /// <summary>
        /// 新增SQL语句
        /// </summary>
        private readonly string addSql = @"insert into SysModule(ID,PID,ModuleName,ModuleUrl,OrderID,ModuleCls,IsDeleted,CreateTime) values (@ID,@PID,@ModuleName,@ModuleUrl,@OrderID,@ModuleCls,@IsDeleted,@CreateTime)";
        /// <summary>
        /// 修改所有字段SQL语句
        /// </summary>
        private readonly string editSql = @"update SysModule set PID=@PID,ModuleName=@ModuleName,ModuleUrl=@ModuleUrl,OrderID=@OrderID,ModuleCls=@ModuleCls,IsDeleted=@IsDeleted,CreateTime=@CreateTime where 1=1";
        /// <summary>
        /// 表主键where条件SQL语句
        /// </summary>
        private readonly string whereByPrimaryKey = @" and ID=@ID";

        public ISysModuleAction_RepositoryService _sysModuleAction_RepositoryService;
        private readonly IEfCore_RepositoryService _efCore_RepositoryService;
        private Entities db;
        public SysModule_RepositoryService(
            ISysModuleAction_RepositoryService sysModuleAction_RepositoryService, IEfCore_RepositoryService efCore_RepositoryService)
        {

            _sysModuleAction_RepositoryService = sysModuleAction_RepositoryService;
            _efCore_RepositoryService = efCore_RepositoryService;
            db = _efCore_RepositoryService.DbContext();
        }

        #region 由软件生成，禁止修改，若需要扩展，请在下方进行扩展

        /// <summary>
        /// 根据主键获取系统模块表资料信息
        /// </summary>
        /// <param name="_iD"></param>
        /// <returns>返回单个系统模块表数据实体</returns>
        public SysModule Get(string _iD)
        {
            string sql = querySql + whereByPrimaryKey;
            DynamicParameters param = new DynamicParameters();
            param.Add("ID", _iD);
            return base.QueryBySql<SysModule>(sql, param);
        }

        /// <summary>
        /// 获取所有记录
        /// </summary>
        /// <param name="_cpnID">企业代码</param>
        /// <returns>返回系统模块表数据集合</returns>
        public List<SysModule> GetAll(string _cpnID)
        {
            return base.QueryListBySql<SysModule>(querySql + " and CpnID=@CpnID", new { CpnID = _cpnID });
        }

        /// <summary>
        /// 获取所有记录
        /// </summary>
        /// <param name="_param">查询条件字典，其中key必须使用字段名</param>
        /// <returns>返回系统模块表数据集合</returns>
        public List<SysModule> GetAll(Hashtable _param)
        {
            //查询SQL语句组装
            string sql = querySql + base.GetQueryConditions(_param);
            //封装参数
            DynamicParameters dynamicParam = new DynamicParameters();
            foreach (string key in _param.Keys)
            {
                dynamicParam.Add(key, _param[key]);
            }

            return base.QueryListBySql<SysModule>(sql, dynamicParam);
        }

        /// <summary>
        /// 按照分页条件查询数据集
        /// </summary>
        /// <param name="_param">查询条件字典，其中key必须使用字段名</param>
        /// <param name="_pageIndex">查询页码，从1开始，必传</param>
        /// <param name="_pageSize">每页查询数据条数，必传</param>
        /// <param name="_sort">排序列名，若要降序请用列名+" DESC"，必传</param>
        /// <param name="_pageCount">返回总页码数</param>
        /// <param name="_dataCount">返回总数据条数</param>
        /// <returns>返回系统模块表数据集合</returns>
        public List<SysModule> GetByPage(Hashtable _param, int _pageIndex, int _pageSize, string _sort, out int _pageCount, out int _dataCount)
        {
            if (_pageIndex == 0 || _pageSize == 0 || string.IsNullOrWhiteSpace(_sort))
            {
                _dataCount = 0;
                _pageCount = 0;
                return null;
            }
            //封装参数
            DynamicParameters dynamicParam = new DynamicParameters();
            foreach (string key in _param.Keys)
                dynamicParam.Add(key, _param[key]);
            //组装计数sql语句
            string countSql = queryCountSql + base.GetQueryConditions(_param);
            _dataCount = base.QueryScalarBySql<Int32>(countSql, dynamicParam);//获取总数据条数
            _pageCount = (_dataCount + _pageSize - 1) / _pageSize;//总页数 =  (数据总条数 + 每页显示条数 - 1) / 每页显示条数
            if (_dataCount == 0)
            {
                return new List<SysModule>();
            }
            //组装分页查询语句
            string sql = querySql + base.GetQueryConditions(_param, _pageIndex, _pageSize, _sort);

            return base.QueryListBySql<SysModule>(sql, dynamicParam);
        }

        /// <summary>
        /// 插入系统模块表数据
        /// </summary>
        /// <param name="_sysModule">需要插入的系统模块表数据实体</param>
        /// <returns>返回影响数据行数</returns>
        public int Add(SysModule _sysModule)
        {
            return base.ExecuteBySql(addSql, _sysModule);
        }

        /// <summary>
        /// 批量插入系统模块表数据
        /// </summary>
        /// <param name="_sysModuleList">需要插入的系统模块表数据集合</param>
        /// <returns>返回影响数据行数</returns>
        public int Add(List<SysModule> _sysModuleList)
        {
            return base.BulkInsert(_sysModuleList);
        }

        /// <summary>
        /// 根据主键更新系统模块表数据
        /// </summary>
        /// <param name="_sysModule">需要更新的系统模块表数据实体</param>
        /// <returns>返回影响数据行数</returns>
        public int Update(SysModule _sysModule)
        {
            return base.ExecuteBySql(editSql + whereByPrimaryKey, _sysModule);
        }

        /// <summary>
        /// 根据主键更新系统模块表指定字段
        /// </summary>
        /// <param name="_sysModule">需要更新的系统模块表数据实体</param>
        /// <param name="_updateProNames">需要更新的字段名</param>
        /// <returns>返回影响数据行数</returns>
        public int Update(SysModule _sysModule, params string[] _updateProNames)
        {
            string sql = @"update SysModule set ";
            sql += base.GetUpdateSet(_updateProNames);
            return base.ExecuteBySql(sql + whereByPrimaryKey, _sysModule);
        }

        #endregion

        /*业务扩展代码*/
        #region 业务扩展代码

        /// <summary>
        /// 获取模块方法
        /// </summary>
        /// <returns></returns>
        public List<LoginModultActionDTO> GetModultAction()
        {
            var sql = "select a.ActionUrl,a.ShowEnum ,a.ActionCls ,a.ActionFun ,a.OrderID,a.ActionName,(case when c.ModuleName is NULL THEN '' else c.ModuleName end ) FatherModuleName,b.ModuleName,a.ModuleID,a.Weight ";
            sql += "from SysModuleAction as a ";
            sql += "LEFT JOIN  SysModule as b on a.ModuleID=b.ID ";
            sql += "LEFT JOIN  SysModule as c on b.PID=c.ID ";
            sql += "where !a.IsDeleted and !b.IsDeleted";
            return base.QueryListBySql<LoginModultActionDTO>(sql);
        }
        public List<SysModule> GetManyModules()
        {
            var sql = "select * from SysModule where IsDeleted=0";
            return base.QueryListBySql<SysModule>(sql);
        }
        /// <summary>
        /// 获取登录菜单
        /// </summary>
        /// <param name="loginUser"></param>
        /// <returns></returns>
        public string GetLoginRoleMenu(LoginUserDTO loginUser)
        {
            StringBuilder sMenu = new StringBuilder();
            var modelList = GetManyModules().OrderBy(x => x.OrderID).ToList();
            if (modelList.Any())
            {
                var parentList = modelList.Where(m => m.PID == Guid.Empty.ToString()).ToList();//获取大模块
                if (parentList != null)
                {
                    foreach (var pModule in parentList)
                    {//遍历大模块
                        var iModuleID = pModule.ID;
                        string sChildJson = InitMenu(iModuleID, modelList, loginUser);
                        if (sChildJson != "'menus':[\r\n]\r\n")
                        {//如果登录用户拥有该大模块权限
                            if (sMenu.Length == 0)
                            {
                                sMenu.AppendLine("{'menus':[");
                            }
                            sMenu.AppendLine("   { " +
                                             InitJsonItem(iModuleID.ToString(), pModule.ModuleName, pModule.ModuleUrl,
                                                 new List<SysModuleAction>(), null, pModule.ModuleCls));//添加大模块菜单
                            sMenu.AppendLine("    " + sChildJson);//添加子模块菜单
                            sMenu.AppendLine("},");
                        }
                    }
                }
                if (sMenu.Length > 0)
                {//添加最后一个]
                    int iDouHaoIndex = sMenu.ToString().LastIndexOf(',');
                    if (iDouHaoIndex != -1)
                    {
                        sMenu = sMenu.Remove(iDouHaoIndex, 1);
                    }
                    sMenu.Append("]}");
                }
            }
            return sMenu.ToString();
        }
        /// <summary>
        /// 加载菜单json
        /// </summary>
        /// <param name="iModuleID"></param>
        /// <param name="modulelist"></param>
        /// <param name="loginUser"></param>
        /// <returns></returns>
        private string InitMenu(string iModuleID, IEnumerable<SysModule> modulelist, LoginUserDTO loginUser)
        {
            StringBuilder sResult = new StringBuilder();
            List<SysModule> childList = modulelist.Where(m => m.PID == iModuleID||m.ID== iModuleID).OrderBy(x => x.OrderID).ToList();//获取子模块菜单
            if (childList.Any())
            {
                var roleids = childList.Select(x => x.ID.ToString());

                var moduleActions = GetmoduleActions(roleids);
                var userActionList = loginUser.UserActionList;//当前登录用户权限
                sResult.AppendLine("'menus':[");
                foreach (var module in childList)
                {
                    string iTempModuleID = module.ID;
                    if (!userActionList.Exists(m => m.ModuleID == iTempModuleID))
                    {
                        //如果用户没有该模块的权限 则检查是否有子模块，否则进入下一个循环
                        var childmodule = modulelist.Where(m => m.PID == iTempModuleID).OrderBy(x => x.OrderID).ToList();//获取三级子模块菜单
                        if (childmodule.Any())
                        {
                            if (userActionList.Exists(m => childmodule.Select(x => x.ID).Contains(m.ModuleID)))
                            {
                                sResult.Append("    {" +
                                               InitChildModuleJsonItem(iTempModuleID.ToString(), module.ModuleName,
                                                   module.ModuleUrl, childmodule, userActionList, module.ModuleCls));
                                sResult.AppendLine("},");
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }
                    else
                    {
                        var ModuleActions = moduleActions.Where(x => x.ModuleID == module.ID).ToList();
                        sResult.Append("    {" + InitJsonItem(iTempModuleID.ToString(), module.ModuleName, module.ModuleUrl, ModuleActions, userActionList, module.ModuleCls));
                        sResult.AppendLine("},");
                    }
                }
                if (childList.Any())
                {
                    sResult.AppendLine("]");
                }
            }
            if (sResult.Length > 0)
            {//添加最后一个]
                int iDouHaoIndex = sResult.ToString().LastIndexOf(',');
                if (iDouHaoIndex != -1)
                {
                    sResult = sResult.Remove(iDouHaoIndex, 1);
                }
            }
            return sResult.ToString();
        }
        private string InitJsonItem(string sID, string menuname, string url, List<SysModuleAction> modelActions, List<RoleActionDTO> userActionList, string ModuleCls)
        {
            StringBuilder sResult = new StringBuilder();
            //sResult.AppendLine("{");
            sResult.Append("'menuid':'" + sID + "',");
            sResult.Append("'menuname':'" + menuname + "',");
            sResult.Append("'modulecls':'" + ModuleCls + "',");
            sResult.Append("'url':'" + url + "',");
            sResult.Append("'ismodule':false,");
            if (userActionList != null)
            {
                sResult.AppendLine("'menus':[");
                if (modelActions.Any())
                {
                    var Weight = 0;
                    modelActions.Where(x => !x.IsDeleted && x.ShowEnum).ToList().ForEach(x =>
                    {
                        var weighlist = userActionList.Where(m => m.ModuleID == sID).ToList();
                        weighlist.ForEach(weightitem =>
                        {
                            if (weightitem != null)
                            {
                                Weight = Weight | weightitem.Weight;
                                if ((Weight & x.Weight) == x.Weight)
                                {
                                    sResult.Append("    {");
                                    sResult.Append("'menuid':'" + x.ID + "',");
                                    sResult.Append("'menuname':'" + x.ActionName + "',");
                                    sResult.Append("'url':'" + x.ActionUrl + "',");
                                    sResult.AppendLine("},");
                                }
                            }
                        });
                        
                    });
                }
                sResult.Append("]");
            }
            //sResult.AppendLine("}");
            return sResult.ToString();
        }
        private string InitChildModuleJsonItem(string sID, string menuname, string url, List<SysModule> childModule, List<RoleActionDTO> userActionList, string ModuleCls)
        {
            StringBuilder sResult = new StringBuilder();
            //sResult.AppendLine("{");
            sResult.Append("'menuid':'" + sID + "',");
            sResult.Append("'menuname':'" + menuname + "',");
            sResult.Append("'modulecls':'" + ModuleCls + "',");
            sResult.Append("'url':'" + url + "',");
            sResult.Append("'ismodule':true,");
            if (childModule != null)
            {
                sResult.AppendLine("'menus':[");
                if (childModule.Any())
                {
                    var roleids = childModule.Select(x => x.ID);
                    var moduleActions = GetmoduleActions(roleids);
                    childModule.Where(x => !x.IsDeleted && userActionList.Select(y => y.ModuleID).Contains(x.ID)).ToList().ForEach(x =>
                    {
                        var ModuleActions = moduleActions.Where(a => a.ModuleID == x.ID).ToList();
                        sResult.Append("    {" + InitJsonItem(x.ID.ToString(), x.ModuleName, x.ModuleUrl, ModuleActions, userActionList, x.ModuleCls));
                        sResult.AppendLine("},");
                    });
                }
                sResult.Append("]");
            }
            //sResult.AppendLine("}");
            return sResult.ToString();
        }
        /// <summary>
        /// 获取模块方法
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public List<SysModuleAction> GetmoduleActions(IEnumerable<string> ids)
        {
            var dbids = new List<string>();
            ids.ToList().ForEach(x =>
            {
                dbids.Add($"'{x}'");
            });
            var roleids = string.Join(",", dbids);
            string sql = $" select * from   SysModuleAction  where  ModuleID in ({roleids})";
            return base.QueryListBySql<SysModuleAction>(sql);
        }

        /// <summary>
        /// 获取树形模块菜单
        /// </summary>
        /// <param name="fatherId"></param>
        /// <param name="itemId"></param>
        /// <returns></returns>
        public dynamic GetFatherModule(string fatherId, string itemId)
        {
            var def = new List<dynamic> { new { Text = "顶级目录", Value = Guid.Empty, Selected = true, PID = Guid.Empty } };
            var space = "";
            var allModule = _efCore_RepositoryService.GetMany(
                new DirectSpecification<SysModule>(x => !x.IsDeleted))
                .Select(
                    x =>
                        new
                        {
                            Text = (x.PID == Guid.Empty.ToString() ? space + "├" : space + space + "├") + x.ModuleName,
                            Value = x.ID,
                            Selected = false,
                            x.PID
                        });
            allModule.Where(x => x.PID == Guid.Empty.ToString()).ToList().ForEach(x =>
            {
                if (fatherId == x.Value)
                {
                    def.Add(new { x.Text, x.Value, Selected = true, PID = Guid.Empty });
                }
                else
                {
                    def.Add(x);
                }
                allModule.Where(y => y.PID == x.Value).ToList().ForEach(y =>
                {
                    if (fatherId == y.Value)
                    {
                        def.Add(new { y.Text, y.Value, Selected = true, PID = Guid.Empty });
                    }
                    else
                    {
                        def.Add(y);
                    }
                });
            });
            return def;
        }

        /// <summary>
        /// 获取模块集合
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="sort"></param>
        /// <param name="moduleParms"></param>
        /// <returns></returns>
        public EntityList<ModuleDTO> GetModuleList(ModuleParmsDTO moduleParms)
        {
            var wheres = PredicateBuilder.True<SysModule>();
            wheres = wheres.And(x => !x.IsDeleted && x.PID == moduleParms.PID);
            if (!string.IsNullOrEmpty(moduleParms.ModuleName))
            {
                wheres = wheres.And(x => x.ModuleName.Contains(moduleParms.ModuleName));
            }
            var dbset = db.Set<SysModule>();
            var query = (from a in dbset.Where(wheres)
                         select new ModuleDTO()
                         {
                             ID = a.ID,
                             ModuleName = a.ModuleName,
                             OrderID = a.OrderID,
                             ModuleCls = a.ModuleCls,
                             ChildModuleCount = db.SysModule.Where(x => !x.IsDeleted && x.PID == a.ID).Count(),
                         });
            EntityList<ModuleDTO> pageData = new EntityList<ModuleDTO>();
            int quyCount = query.Count();
            if (quyCount > 0)
            {
                pageData.Data = query.ToList();
            }
            //var data = FindAllAsQueryPage<ModuleDTO>(query, page, rows);
            pageData.Data.ForEach(x =>
            {
                x.hasChildren = x.ChildModuleCount > 0;
            });
            return pageData;
        }
        /// <summary>
        /// 获取当前模块下级模块
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="moduleParms"></param>
        /// <returns></returns>
        public EntityList<ModuleDTO> GetModuleListByPid(ModuleParmsDTO moduleParms)
        {
            var wheres = PredicateBuilder.True<SysModule>();
            wheres = wheres.And(x => !x.IsDeleted && x.PID == moduleParms.PID);
            var dbset = db.Set<SysModule>();
            var query = (from a in dbset.Where(wheres)
                         select new ModuleDTO()
                         {
                             ID = a.ID,
                             ModuleName = a.ModuleName,
                             OrderID = a.OrderID,
                             ModuleCls = a.ModuleCls,
                             ChildModuleCount = db.SysModule.Where(x => !x.IsDeleted && x.PID == a.ID).Count(),
                         });
            EntityList<ModuleDTO> pageData = new EntityList<ModuleDTO>();
            int quyCount = query.Count();
            if (quyCount > 0)
            {
                pageData.Data = query.ToList();
            }
            pageData.Data.ForEach(x =>
            {

                x.hasChildren = x.ChildModuleCount > 0;
            });
            return pageData;
        }
        /// <summary>
        /// 获取当前模块下所有功能菜单
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="moduleParms"></param>
        /// <returns></returns>
        public EntityList<SysModuleAction> GetSysModuleActionLst(int page, int rows, SysModuleActionParms sysModuleActionParms)
        {
            var wheres = PredicateBuilder.True<SysModuleAction>();

            if (!string.IsNullOrEmpty(sysModuleActionParms.ModuleId))
            {
                wheres = wheres.And(x => x.ModuleID == sysModuleActionParms.ModuleId);
            }
            var query = (from a in db.SysModuleAction.Where(x => !x.IsDeleted).Where(wheres)
                         select a);


            var result = new EntityList<SysModuleAction>();
            result = _efCore_RepositoryService.FindAllAsQuery<SysModuleAction>(query, page, rows);
            return result;
        }
        /// <summary>
        /// 获取菜单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public SysModuleAction GetSysModuleActionById(string id)
        {
            if (id == null || !_efCore_RepositoryService.Exists(new DirectSpecification<SysModuleAction>(x => !x.IsDeleted && x.ID == id)))
            {
                throw new UNException("未找到当前数据,请刷新页面后尝试");
            }
            return _efCore_RepositoryService.GetByKey<SysModuleAction>(id);
        }
        /// <summary>
        /// 获取模块详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public SysModule GetmoduleById(string id)
        {
            if (id == null || !_efCore_RepositoryService.Exists(new DirectSpecification<SysModule>(x => !x.IsDeleted && x.ID == id)))
            {
                throw new Exception("未找到当前数据,请刷新页面后尝试");
            }
            return _efCore_RepositoryService.GetByKey<SysModule>(id);
        }
        #endregion
    }
}
